<template>
  <div class="table-box">
    <!-- 公司列表 -->
    <div v-show="!showFleetList">
      <el-card>
        <template #header>
          <div class="flex justify-between items-center">
            <span class="font-medium">公司车队管理</span>
            <el-button type="primary" :icon="CirclePlus" @click="openCompanyForm('新增公司')">
              新增公司
            </el-button>
          </div>
        </template>
        
        <ProTable
          ref="companyTableRef"
          :columns="companyColumns"
          :search-columns="companySearchColumns"
          :request-api="getCompanyList"
          row-key="id"
        >
          <template #operation="{ row }">
            <el-button
              type="primary"
              link
              :icon="View"
              @click="showFleet(row)"
            >
              查看车队
            </el-button>
            <el-button
              type="primary"
              link
              :icon="CirclePlus"
              @click="openFleetForm('新增车队', {}, row.id)"
            >
              新增车队
            </el-button>
            <el-button
              type="primary"
              link
              :icon="EditPen"
              @click="openCompanyForm('编辑公司', row)"
            >
              编辑
            </el-button>
            <el-button
              type="primary"
              link
              :icon="Delete"
              @click="deleteCompany(row)"
            >
              删除
            </el-button>
          </template>
        </ProTable>
      </el-card>
    </div>
    
    <!-- 车队列表 -->
    <div v-show="showFleetList">
      <el-page-header @back="goBack">
        <template #content>
          <span class="text-large font-600 mr-3"> {{ currentCompany?.name }} - 车队列表 </span>
        </template>
      </el-page-header>
      <FleetList v-if="currentCompany" :company-id="currentCompany.id" />
    </div>
    
    <!-- 公司表单 -->
    <CompanyForm ref="companyFormRef" />
    
    <!-- 车队表单 -->
    <FleetForm ref="fleetFormRef" />
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import { CirclePlus, EditPen, Delete, View } from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import ProTable from '@/components/ProTable/index.vue';
import {
  getCompanyListApi,
  createCompanyApi,
  updateCompanyApi,
  removeCompanyApi,
  createFleetApi,
  updateFleetApi,
  removeFleetApi
} from '@/api/modules/dept/dept';
import { useHandleData } from '@/hooks/useHandleData';
import CompanyForm from '@/views/dept/deptList/components/CompanyForm.vue';
import FleetForm from '@/views/dept/deptList/components/FleetForm.vue';
import FleetList from '@/views/dept/deptList/components/FleetList.vue';
import type { ColumnProps, ProTableInstance, SearchProps } from '@/components/ProTable/interface';
import type { DeptQuery, DeptRow } from '@/api/types/dept/dept';

defineOptions({
  name: 'DeptListView'
});

// 控制显示哪个页面
const showFleetList = ref(false);
const currentCompany = ref<DeptRow | null>(null);

// 表格引用
const companyTableRef = ref<ProTableInstance>();

// 表单引用
const companyFormRef = ref<InstanceType<typeof CompanyForm>>();
const fleetFormRef = ref<InstanceType<typeof FleetForm>>();

// 公司表格配置项
const companyColumns: ColumnProps<DeptRow>[] = [
  { prop: 'name', label: '公司名称', width: 250 },
  { prop: 'sort', label: '排序', width: 100 },
  { 
    prop: 'leaders', 
    label: '负责人',
    width: 200,
    render: ({ row }) => {
      if (row.leaders && row.leaders.length > 0) {
        return row.leaders.map((leader: any) => leader.name).join(', ');
      }
      return '-';
    }
  },
  { prop: 'createTime', label: '创建时间', },
  { prop: 'updateTime', label: '更新时间', width: 180 },
  { prop: 'operation', label: '操作', width: 300, fixed: 'right' }
];

// 公司搜索条件项
const companySearchColumns: SearchProps[] = [
  { prop: 'name', label: '公司名称', el: 'input' }
];

// 获取公司列表（分页）
const getCompanyList = (params: DeptQuery) => {
  return getCompanyListApi(params);
};

// 打开公司表单（新增/编辑）
const openCompanyForm = (title: string, row: any = {}) => {
  const params = {
    title,
    row: { ...row },
    api: row.id ? updateCompanyApi : createCompanyApi,
    getTableList: companyTableRef.value?.getTableList
  };
  companyFormRef.value?.acceptParams(params);
};

// 打开车队表单（新增/编辑）
const openFleetForm = (title: string, row: any = {}, companyId?: number) => {
  const params = {
    title,
    row: { ...row },
    companyId, // 传递公司ID
    api: row.id ? updateFleetApi : createFleetApi,
    getTableList: companyTableRef.value?.getTableList
  };
  fleetFormRef.value?.acceptParams(params);
};

// 删除公司
const deleteCompany = async (row: DeptRow) => {
  if (row.children && row.children.length > 0) {
    ElMessage.warning('该公司下有车队，无法删除');
    return;
  }
  
  ElMessageBox.confirm(`确定要删除公司【${row.name}】吗？`, '提示', {
    type: 'warning'
  }).then(async () => {
    try {
      await useHandleData(removeCompanyApi, { ids: [row.id.toString()] }, `删除【${row.name}】公司`);
      companyTableRef.value?.getTableList();
    } catch (error) {
      console.error('删除公司失败:', error);
    }
  }).catch(() => {
    // 取消删除
  });
};

// 显示车队列表
const showFleet = (row: DeptRow) => {
  currentCompany.value = row;
  showFleetList.value = true;
};

// 返回公司列表
const goBack = () => {
  showFleetList.value = false;
  currentCompany.value = null;
};
</script>

<style scoped lang="scss">
.table-box {
  padding: 20px;
}

.flex {
  display: flex;
}

.justify-between {
  justify-content: space-between;
}

.items-center {
  align-items: center;
}

.font-medium {
  font-weight: 500;
}

.text-large {
  font-size: 18px;
}

.font-600 {
  font-weight: 600;
}

.mr-3 {
  margin-right: 12px;
}
</style>